import { Component, OnInit, ViewChild, AfterViewInit, OnDestroy } from '@angular/core';
import { HttpService } from 'src/app/service/http.service';
import { ToolService } from 'src/app/service/tool.service';
import { IonSlides, NavController, Platform } from '@ionic/angular';
import { UrlService } from 'src/app/service/url.service';
import { ConfigService } from 'src/app/service/config.service';
import { Router } from '@angular/router';
import * as $ from 'jquery';
import { PopwinService } from 'src/app/service/popwin.service';
import { Storage } from '@ionic/storage';
import { EventService } from 'src/app/service/event.service';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';


@Component({
  selector: 'app-index',
  templateUrl: './index.page.html',
  styleUrls: ['./index.page.scss'],
})
export class IndexPage implements OnInit,AfterViewInit,OnDestroy {
  imgArr = [];
  url = ConfigService.SERVER_PATH;
  @ViewChild('slides') slides;
  slideOpts = {
    effect: 'flip',  //轮播效果
    autoplay: {
      delay: 2000,
    },
    loop:true
  };
  firstFlag = true; secodFlag = false; thirdFlag = false;
  markIndex = -1;
  lots = [];
  lots1 = [];
  lots2 = [];
  nowTime;
  objectKeys = Object.keys;
  noticeArr = [];
  private allTimerArr = []; private hotTimerArr = []; private collectTimerArr = [];
  private tempRefreshTimeNetArr:any[]=[];
  public isNoDevice:boolean=false;
  private isOpen:boolean=true;
  constructor(private http: HttpService, private navCtrl: NavController, private router: Router, private popWin: PopwinService, private eventS: EventService, private store: Storage,private platform :Platform,private iab:InAppBrowser) { }

  ngOnInit() {
    //console.log("-", ToolService.aesEncode("Hello123"));
    if(ConfigService.is3rd){
      this.navCtrl.navigateRoot("/tabs/index3rd");
      return;
    }
    this.menuNet();
    this.test();
    this.noticeData();
    this.sliderData();
    this.initEvent();
    if(!this.platform.is("cordova")){
        this.isNoDevice=true;
    }
  }

  doRefresh(event) {
    this.menuNet();
    this.timeNet();
    setTimeout(() => {
      event.target.complete();
    }, 2000);
  }

  initEvent() {
    let that = this;
    this.eventS.subscribe("updateMenu", function () {//登录更新菜单的数据,和加载时间
      that.menuNet();
      that.timeNet();
    }, true);

    this.eventS.subscribe("indexClearTimeOut", function () {//清除计时器
      that.clearAllTimeOut();
    }, true);

    this.eventS.subscribe("indexStartTime", function () {//启动计时器器
      that.timeNet();
      that.autoPlay();//  启动自动滚动的方法
    }, true);

  }
  /**
    * 加载菜单
    */
  menuNet() {
    let that = this;
    this.http.get(UrlService.USER_MAIN_HALL, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      that.setSessid(data.ssid);
      if (data.code == ConfigService.SUCCESS_CODE) {
        that.lots = []; //热门彩种
        that.lots1 = []; //所有彩种
        that.lots2 = [];  //我的收藏
        let temp = data.data;
        that.store.set(ConfigService.ALL_LOT_STORE_KEY, ToolService.aesDecodeToJson(ToolService.aesDecodeToJson(temp).lots.all));   
        let tt = ToolService.aesDecode(temp);
        tt = JSON.parse(tt).lots;
        that.lots=tt.hot;
        that.lots1=tt.all;
        let allLot=tt.all;
        for (let tempData in allLot) {
          that.store.get(ConfigService.IS_LOGIN_STORE_KEY).then((data) => {
            if (!ToolService.isEmpty(data)) {//未登录进行登录
              if (allLot[tempData].is_follow == 1) {
                that.lots2.push(allLot[tempData]);
              }
            }
          });
        }
      } else if (data.code == ConfigService.FAIL_CODE) {
        // this.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        this.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  timeNet() {
    let that = this;
    this.http.get(UrlService.USER_TIME, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      that.setSessid(data.ssid);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let temp = data.data;
        let tt = ToolService.aesDecodeToJson(temp);
        console.log("所有的时间", tt);
        that.clearAllTimeOut();
        //热门彩种的时间处理
        for (let t1 in that.lots) {
          that.lots[t1]['closeTime'] = "";
          for (let t11 in tt.times) {
            if (that.lots[t1].key == t11) {
              that.lots[t1]['closeTime'] = (tt.times[t11] - tt.now);
            }
          }
        }
        //所有彩种时间处理
        for (let t1 in that.lots1) {
          that.lots1[t1]['closeTime'] = "";
          for (let t11 in tt.times) {
            if (that.lots1[t1].key == t11) {
              that.lots1[t1]['closeTime'] = (tt.times[t11] - tt.now);
            }
          }
        }
        //我的关注的时间处理
        for (let t1 in that.lots2) {
          that.lots2[t1]['closeTime'] = "";
          for (let t11 in tt.times) {
            if (that.lots2[t1].key == t11) {
              that.lots2[t1]['closeTime'] = (tt.times[t11] - tt.now);
            }
          }
        }
        setTimeout(function () {
          that.countdownFun(".hot-lots");
          that.countdownFun(".all-hots");
          that.countdownFun(".collect-lots");
        }, 10);
        that.clearTimer(that.tempRefreshTimeNetArr,true);
        that.tempRefreshTimeNetArr=[];
        let tempRefreshTimeNet = setTimeout(function () {
          that.timeNet();
          clearTimeout(tempRefreshTimeNet);
        }, 10000);
        that.tempRefreshTimeNetArr.push(tempRefreshTimeNet);
      } else if (data.code == ConfigService.FAIL_CODE) {
        // this.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        this.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }
  //
  test() {
    //   let that=this;
    //   this.http.get("http://app.tw8999.com/test/test",{"callback":"JSONP_CALLBACK"}).subscribe(res=>{
    //     let data = res.json();
    //     let temp= data.data;
    //     let tt= ToolService.aesDecode(temp);
    //     this.popWin.toast(tt);
    //     console.log("===========================================");
    //   //  tt=JSON.parse(tt);
    //     console.log(tt);
    //     console.log("===========================================");
    //  },error=>{
    //     console.log("error",error);
    //  });
  }

  
  onStoreFun(lotteryId, is_follow) {
    event.stopPropagation();
    if (is_follow != 1) {//关注的逻辑
      this.storeNet(lotteryId, 1);
    } else {//取消关注
      this.storeNet(lotteryId, 2);
    }
  }

  storeNet(lotteryId, is_follow) {
    let that = this;
    let obj = "{\"lotteryId\":\"" + lotteryId + "\",\"is_follow\":\"" + is_follow + "\"}";
    console.log(obj);
    this.http.get(UrlService.USER_FOLLOW, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      that.setSessid(data.ssid);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let temp = data.data;
        let tt = ToolService.aesDecode(temp);
        that.menuNet();
        that.timeNet();
        //  console.log(tt);
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }
  /**
   * 首页的公共文件
   */
  noticeData() {
    let that = this;
    this.http.get(UrlService.USER_CONTENT, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      that.setSessid(data.ssid);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let temp = data.data;
        that.noticeArr = ToolService.aesDecodeToJson(temp);
        if (ToolService.isEmpty(that.noticeArr+"") || ToolService.isEmpty(that.noticeArr)) {
          that.noticeArr = [];
        }else{
          let t=setTimeout(function(){
            that.marqueeFun();
            clearTimeout(t);
          },200);
        }
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  sliderData() {
    let that = this;
    this.http.get(UrlService.USER_BANNER, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      that.setSessid(data.ssid);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let temp = data.data;
        that.imgArr = ToolService.aesDecodeToJson(temp);
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  /**
   * 倒计时
   */
  countdownFun(obj: string) {
    let that = this;
    let timeArr = [];
    if (obj == ".hot-lots") {
      this.clearTimer(this.hotTimerArr);
      this.hotTimerArr = [];
    } else if (obj == ".all-hots") {
      this.clearTimer(this.allTimerArr);
      this.allTimerArr = [];
    } else if (obj == ".collect-lots") {
      this.clearTimer(this.collectTimerArr);
      this.collectTimerArr = [];
    }
    $(obj + " .m-t-time").each(function (index) {
      if ($(this).attr("data-value") == "1") {
        let tempObj = $(obj + " .m-t-time").eq(index);
        let temp = parseInt(tempObj.attr("id"));
        let timer = setInterval(function () {
          if (temp <= 0) {
            $(obj + " .m-t-time").eq(index).html("已封盘");
            $(obj + " .m-t-time").eq(index).css("color","#d31111");
            return;
          }
          temp--;
          if (ToolService.isNumber("" + temp)) {
            if ($(obj + " .m-t-time").eq(index).attr("data-code") == 'lhc' || $(obj + " .m-t-time").eq(index).attr("data-code") == 'f3d' || $(obj + " .m-t-time").eq(index).attr("data-code") == 'pl3') {
              tempObj.html(ToolService.formateTime(temp));
            } else {
              tempObj.html(ToolService.formateTime(temp, true));
            }
            $(obj + " .m-t-time").eq(index).css("color","#0070c0");
          }
        }, 1000);
        timeArr.push(timer);
      }
    });
    if (obj == ".hot-lots") {
      this.hotTimerArr = timeArr;
    } else if (obj == ".all-hots") {
      this.allTimerArr = timeArr;
    } else if (obj == ".collect-lots") {
      this.collectTimerArr = timeArr;
    }
  }
  //清除计时器，并清空数据
  clearTimer(timer,isTimeOut?:boolean) {
    if (timer.length > 0) {
      for (let i = 0; i < timer.length; i++) {
        if(isTimeOut){
          clearTimeout(timer[i]);
        }else{
          clearInterval(timer[i]);
        }
        timer[i]=null;
      }
    }
  }

  onSelectMenu(mark) {
    if (this.markIndex != mark) {
      if (mark == 1) {
        this.firstFlag = true; this.secodFlag = false; this.thirdFlag = false;
      } else if (mark == 2) {
        this.firstFlag = false; this.secodFlag = true; this.thirdFlag = false;
      } else if (mark == 3) {
        this.firstFlag = false; this.secodFlag = false; this.thirdFlag = true;
      }
      this.markIndex = mark;
    }
    this.store.get(ConfigService.IS_LOGIN_STORE_KEY).then((data) => {
      if (ToolService.isEmpty(data) && mark == 3) {//未登录进行登录
        this.navCtrl.navigateForward("/login");
        return;
      }
    });
  }

  async toLotdetail(key, name, lotteryId) {
    this.clearAllTimeOut();
    let that = this;
    await this.store.get(ConfigService.IS_LOGIN_STORE_KEY).then((data) => {
      if (ToolService.isEmpty(data)) {//未登录进行登录
        this.navCtrl.navigateForward("/login");
        return;
      } else {
        let param = "{\"code\":\"" + key + "\",\"name\":\"" + name + "\",\"lotteryId\":\"" + lotteryId + "\"}";
        that.router.navigate(['/lotdetail'], {
          queryParams: { "p": ToolService.paramAESEncrypt(param)}
        });

      }
    });
  }

  autoPlay() {
    this.slides.stopAutoplay();
    this.slides.startAutoplay();
  }

  /**
   * 清除首页的倒计时的计时器
   */
  clearAllTimeOut() {
    let that = this;
    that.clearTimer(that.tempRefreshTimeNetArr,true);
    that.tempRefreshTimeNetArr=[];
    that.clearTimer(that.hotTimerArr);
    that.hotTimerArr = [];
    that.clearTimer(that.allTimerArr);
    that.allTimerArr = [];
    that.clearTimer(that.collectTimerArr);
    that.collectTimerArr = [];
  }


  ngAfterViewInit() {
    this.timeNet();
    this.autoPlay();
  }
  ngOnDestroy() {
    this.slides.stopAutoplay();
    this.clearAllTimeOut();
  }
  marqueeFun(){
    if(this.noticeArr.length<=0){
       return;
   }
   let speed=60//速度数值越大速度越慢
     let colee_left2=document.getElementById("n-c-copy");
     let colee_left1=document.getElementById("n-c");
     let widthV=0;
     $("#n-c p").each(function(index){
       let xx=	$("#n-c p").eq(index).width();
       widthV+=xx
     });
     $("#n-c-contain").css("width",2*widthV+"px");
     $("#n-c,#n-c-copy").css("width",widthV+"px");
     let colee_left=document.getElementById("notice-contain");
     colee_left2.innerHTML=colee_left1.innerHTML
     function Marquee3(){
       if(colee_left2.offsetWidth-colee_left.scrollLeft<=0){//offsetWidth 是对象的可见宽度
         colee_left.scrollLeft-=colee_left1.offsetWidth;//scrollWidth 是对象的实际内容的宽，不包边线宽度
       }else{
         colee_left.scrollLeft++;
       }
     }
     let MyMar3=setInterval(Marquee3,speed);  
 }

  setSessid(sessid){
    $("app-root").attr("sessid",sessid);
  }
  /**
   * 关闭那个气泡的界面
   */
  closeContain(){
    $(".download-contain").css("display","none");
  }
  /**
   * 打开下载app的那个单页面
   */
  openDownPage(){
    if(this.isOpen){
      this.isOpen=false;
      this.recommendData();
    }
  }

 async recommendData() {
    let that = this;
    await that.store.get(ConfigService.RECOMMEND).then((data)=>{
        that.isOpen=true;
        if(!ToolService.isEmpty(data)){
          that.toLink(data.mobile.cfg_val);
            return;
        }
    });
    let obj = "{\"type\":\"" + "recommend" + "\"}";
    this.http.get(UrlService.OTHER_CONFIG, { "callback": "JSONP_CALLBACK" , "data": ToolService.aesEncode(obj)}).subscribe(res => {
      that.isOpen=true;
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let temp = data.data;
        let res = ToolService.aesDecodeToJson(temp);
        that.store.set(ConfigService.RECOMMEND,res);
        that.toLink(res.mobile.cfg_val);
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
       
      }
    }, error => {
      that.isOpen=true;
      console.log("error", error);
    });
  }

  toLink(url){
    this.iab.create(url, '_system');
  }

  /**
   * 跳转到公告列表的页面去
   */
  toNoticeList(){
     this.clearAllTimeOut();
     this.navCtrl.navigateForward("/notice");
  }

  /**
   * 顶部是否隐藏banner的业务逻辑
   */
  hideSlider(){
    if($(".slide-h-btn.iconfont").hasClass("ion-ios-fanhui1-down")){
      $(".slide-h-btn.iconfont").removeClass("ion-ios-fanhui1-down").addClass("ion-ios-fanhui1-up");
      $(".slide-contain").css("display","none");
      $(".notice-contain").css("margin-top","-10px");
      $("#noticeItem").css("margin-top","-3px");
    }else{
      $(".slide-h-btn.iconfont").removeClass("ion-ios-fanhui1-up").addClass("ion-ios-fanhui1-down");
      $(".slide-contain").css("display","block");
      $(".notice-contain").css("margin-top","-12px");
      $("#noticeItem").css("margin-top","-5px");
    }
  }


}
